/*
 * Project Name: jmax
 * File Name: FilterTranslatorServiceImpl.java
 * Copyright: Copyright(C) 1985-2015 ZKTeco Inc. All rights reserved.
 */
package com.xdtech.sys.service.impl;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.Reader;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.thoughtworks.xstream.XStream;
import com.xdtech.common.exception.BusinessException;
import com.xdtech.common.utils.EmptyUtil;
import com.xdtech.core.model.BaseItem;
import com.xdtech.sys.dao.FilterTranslatorDao;
import com.xdtech.sys.init.SysInit;
import com.xdtech.sys.model.DictionaryCode;
import com.xdtech.sys.model.FilterGroup;
import com.xdtech.sys.model.FilterTranslator;
import com.xdtech.sys.service.FilterGroupService;
import com.xdtech.sys.service.FilterRuleService;
import com.xdtech.sys.service.FilterTranslatorService;
import com.xdtech.sys.util.SysConstants;
import com.xdtech.sys.vo.FilterGroupItem;
import com.xdtech.sys.vo.FilterRuleItem;
import com.xdtech.sys.vo.FilterTranslatorItem;
import com.xdtech.sys.vo.UserItem;
import com.xdtech.web.model.Pagination;

/**
 * TODO 一句话功能简述，请确保和下面的block tags之间保留一行空行
 * <p>
 * TODO 功能详细描述，若不需要请连同上面的p标签一起删除
 * 
 * @author <a href="max.zheng@zkteco.com">郑志雄</>
 * @version TODO 添加版本
 * @see 相关类或方法，不需要请删除此行
 * @since 2015-3-19 上午9:26:58
 */
@Service
public class FilterTranslatorServiceImpl implements FilterTranslatorService
{
	@Autowired
	private FilterTranslatorDao filterTranslatorDao;
	@Autowired
	private FilterGroupService filterGroupService;
	@Autowired
	private FilterRuleService filterRuleService;
	/* (非 Javadoc)
	 * save
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param entity
	 * @see com.xdtech.common.service.IBaseService#save(com.xdtech.core.model.BaseModel)
	 */
	@Override
	public void save(FilterTranslator entity)
	{
		filterTranslatorDao.save(entity);
	}

	/* (非 Javadoc)
	 * saveAll
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param entities
	 * @see com.xdtech.common.service.IBaseService#saveAll(java.util.List)
	 */
	@Override
	public void saveAll(List<FilterTranslator> entities)
	{
		filterTranslatorDao.saveAll(entities);
	}

	/* (非 Javadoc)
	 * delete
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param entity
	 * @see com.xdtech.common.service.IBaseService#delete(com.xdtech.core.model.BaseModel)
	 */
	@Override
	public void delete(FilterTranslator entity)
	{
		filterTranslatorDao.delete(entity);
	}

	/* (非 Javadoc)
	 * delete
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param id
	 * @see com.xdtech.common.service.IBaseService#delete(java.lang.Long)
	 */
	@Override
	public void delete(Long id)
	{
		filterTranslatorDao.delete(id);
	}

	/* (非 Javadoc)
	 * get
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param id
	 * @return
	 * @see com.xdtech.common.service.IBaseService#get(java.lang.Long)
	 */
	@Override
	public FilterTranslator get(Long id)
	{
		return filterTranslatorDao.get(id);
	}

	/* (非 Javadoc)
	 * getAll
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @return
	 * @see com.xdtech.common.service.IBaseService#getAll()
	 */
	@Override
	public List<FilterTranslator> getAll()
	{
		return filterTranslatorDao.getAll();
	}

	/* (非 Javadoc)
	 * loadPageAndCondition
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param pg
	 * @param values
	 * @return
	 * @see com.xdtech.common.service.IBaseService#loadPageAndCondition(com.xdtech.web.model.Pagination, java.util.Map)
	 */
	@Override
	public Map<String, Object> loadPageAndCondition(Pagination pg, Map<String, String> values)
	{
		return null;
	}

	/* (非 Javadoc)
	 * deleteByResourceId
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param id
	 * @see com.xdtech.sys.service.FilterTranslatorService#deleteByResourceId(java.lang.Long)
	 */
	@Override
	public void deleteByResourceId(Long id)
	{
		FilterTranslator filterTranslator = getTranslatorByResourceId(id);
		filterGroupService.deleteByTranslator(filterTranslator);
		filterTranslatorDao.delete(filterTranslator);
		
	}

	/* (非 Javadoc)
	 * createTranslatorByResourceKey
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param resourceKey
	 * @param userId
	 * @param roleIds
	 * @param groupIds
	 * @return
	 * @see com.xdtech.sys.service.FilterTranslatorService#createTranslatorByResourceKey(java.lang.String, java.lang.Long, java.util.List, java.util.Set)
	 */
	@Override
	public String createTranslatorByResourceKey(String resourceKey,UserItem currentUser)
	{
		
//		FilterTranslator filterTranslator = (FilterTranslator) filterTranslatorDao.excuteSql("select * from SYS_FILTER_TRANSLATOR where resource_id=(select id from sys_resource where resource_key=?)", resourceKey);
		
		FilterTranslator filterTranslator = filterTranslatorDao.findUnique("from FilterTranslator where resouceId=(select id from Resource where key=?)", resourceKey);
		XStream xstream = new XStream(); 
	    FilterTranslatorItem translatorItem = (FilterTranslatorItem) xstream.fromXML(filterTranslator.getXml());
		
		StringBuffer conditions = new StringBuffer("");
		List<FilterGroupItem> groupItems = translatorItem.getGroups();
		for (FilterGroupItem groupItem : groupItems) {
			conditions.append(" "+groupItem.getOption()+" (");
			List<FilterRuleItem> ruleItems = groupItem.getRules();
			for (FilterRuleItem ruleItem : ruleItems) {
//				if (StringUtils.isNotBlank(ruleItem.getOption())) {
//					conditions.append(ruleItem.getOption());
//				}
				conditions.append(createRuleCondition(ruleItem,currentUser));
//				conditions.append("");
			}
			conditions.append(")");
		}
//		if (filterTranslator!=null) {
//			content = filterTranslator.getText();
//			content = content.replace(SysConstants.CURRENT_USER_ID, userId+"");
//			//此处需考虑一人多角色和一人多用户组情况，后续整改
//			if (EmptyUtil.isNotEmpty(roleIds))
//			{
//				content = content.replace(SysConstants.CURRENT_ROLE_IDS, roleIds.get(0)+"");
//			}
//		
//			if (EmptyUtil.isNotEmpty(groupIds))
//			{
//				content = content.replace(SysConstants.CURRENT_GROUP_IDS, groupIds.iterator().next()+"");
//			}
//		}
		
		return conditions.toString();
	}

	/**
	 * 
	 * @author max.zheng
	 * @create 2015-3-22下午7:51:05
	 * @modified by
	 * @param ruleItem
	 * @return
	 */
	private String createRuleCondition(FilterRuleItem ruleItem,UserItem currentUser) {
		Long userId = currentUser.getId();
		List<Long> roleIds = currentUser.getRoleIds();
		List<Long> groupIds = currentUser.getUsergroupIds();
		
		StringBuffer ruleConditions = new StringBuffer(" ");
		if (StringUtils.isNotBlank(ruleItem.getOption())) {
			ruleConditions.append(ruleItem.getOption());
		}
		ruleConditions.append("(");
		if(SysConstants.CURRENT_ROLE_IDS.equals(ruleItem.getField()))
		{
			
			if ("eq".equals(ruleItem.getType())) {
				if (EmptyUtil.isEmpty(roleIds))
				{
					//空的默认-1
					ruleConditions.append(ruleItem.getValue()+" in (-1) ");
				}else
				{
					ruleConditions.append(ruleItem.getValue()+" in "+roleIds.toString().replace("[", "(").replace("]", ") "));
				}
				
			}else if ("in".equals(ruleItem.getType())) {
				//角色组 1,2,3,45,
				for (int i = 0; i < roleIds.size(); i++)
				{
					if (i==0)
					{
						ruleConditions.append(" "+roleIds.get(i)+" in ("+ruleItem.getValue()+") ");
					}else
					{
						ruleConditions.append(" or "+roleIds.get(i)+" in ("+ruleItem.getValue()+") ");
					}
				}
				
			}
			
		}else if (SysConstants.CURRENT_GROUP_IDS.equals(ruleItem.getField()))
		{
			//用户组 1,2,3,45
			if ("eq".equals(ruleItem.getType())) {
				if (EmptyUtil.isEmpty(groupIds))
				{
					//空的默认-1
					ruleConditions.append(ruleItem.getValue()+" in (-1) ");
				}else
				{
					ruleConditions.append(ruleItem.getValue()+" in "+groupIds.toString().replace("[", "(").replace("]", ") "));
				}
			}else if ("in".equals(ruleItem.getType())) {
				//用户组 1,2,3,45,
				for (int i = 0; i < groupIds.size(); i++)
				{
					if (i==0)
					{
						ruleConditions.append(" "+groupIds.get(i)+" in ("+ruleItem.getValue()+") ");
					}else
					{
						ruleConditions.append(" or "+groupIds.get(i)+" in ("+ruleItem.getValue()+") ");
					}
				}
			}
		}
//		else if (SysConstants.CURRENT_USER_ID.equals(ruleItem.getField()))
		else 
		{
			String field = "";
			if (SysConstants.CURRENT_USER_ID.equals(ruleItem.getField()))
			{
				field = userId+"";
			}
			else
			{
				field = ruleItem.getField();
			}
			//默认都是根据用户id关联处理，目前业务表字段关联只能关联到用户id，作为业务标记才可以
			if ("eq".equals(ruleItem.getType())) {
				ruleConditions.append(field+"="+ruleItem.getValue()+" ");
			}else if ("in".equals(ruleItem.getType())) {
				ruleConditions.append(field+" in ("+ruleItem.getValue()+") ");
			}
			
		}
		ruleConditions.append(")");
		return ruleConditions.toString();
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-3-22上午12:02:59
	 * @modified by
	 * @param resourceId
	 * @param translator
	 */
	@Override
	public void saveTranslatorHasLinkInfo(Long resourceId,
			FilterTranslator translator) {
		List<FilterGroup> groups = translator.getGroups();
		translator.setResouceId(resourceId);
		save(translator);
		filterGroupService.saveGroupsLinkRule(translator,groups);
	}

	/* (非 Javadoc)
	 * getTranslatorByResourceId
	 * <p>对override方法的补充说明，若不需要则删除此行</p>
	 * 
	 * @param resourceId
	 * @see com.xdtech.sys.service.FilterTranslatorService#getTranslatorByResourceId(java.lang.Long)
	 */
	@Override
	public FilterTranslator getTranslatorByResourceId(Long resourceId)
	{
		FilterTranslator filterTranslator = filterTranslatorDao.findUnique("from FilterTranslator where resouceId=?", resourceId);
		return filterTranslator;
	}

	/**
	 * @description
	 * @author max.zheng
	 * @create 2015-4-18下午12:24:42
	 * @modified by
	 * @param pg
	 * @param baseItem
	 * @param queryName
	 * @return
	 */
	@Override
	public Map<String, Object> loadPageDataByConditions(Pagination pg,
			BaseItem baseItem, String queryName) {
		// TODO Auto-generated method stub
		return null;
	}

}
